<template>
  <scroll-view scroll-y class="viewport">
    <!-- 基本信息 -->
    <view class="goods">
      <!-- 古树图片 -->
      <view class="preview">
        <swiper v-if="treeDetail.mediaList && treeDetail.mediaList.length > 0" @change="handleSwiperChange" circular
          class="swiper" indicator-dots indicator-color="rgba(255, 255, 255, 0.4)" indicator-active-color="#35c8a9"
          autoplay interval="5000" duration="500">
          <swiper-item v-for="item in treeDetail.mediaList" :key="item.mediaId">
            <image @tap="onTapImage(item.mediaUrl)" class="image" mode="aspectFill" :src="item.mediaUrl"
              @error="onImageError(item)" />
          </swiper-item>
        </swiper>
        <!-- 无图片时显示 -->
        <view v-else class="no-image">
          <text class="iconfont icon-tree"></text>
          <text class="no-image-text">暂无图片</text>
        </view>
        <view class="indicator" v-if="treeDetail.mediaList && treeDetail.mediaList.length > 0">
          <text class="current">{{ currentIndex + 1 }}</text>
          <text class="split">/</text>
          <text class="total">{{ treeDetail.mediaList.length }}</text>
        </view>
      </view>

      <!-- 古树简介 -->
      <view class="meta">
        <view class="name-wrapper">
          <view class="name ellipsis">{{ treeDetail.chineseName }} {{ treeDetail.scientificName }}</view>
          <view class="age-badge">古树名木</view>
        </view>
        <view class="desc">
          <text class="age-icon">🕐</text>
          距今约{{ treeDetail.estimatedAge }} 年
        </view>
      </view>
    </view>


    <!-- 志愿活动按钮 -->
    <view>
      <button class="form-button" @tap="onAddVolunteerActivity">添加志愿活动</button>
    </view>

    <!-- 古树详情 -->
    <view class="detail panel">
      <view class="title">
        <text class="title-text">详情信息</text>
        <view class="title-line"></view>
      </view>
      <view class="content">
        <view class="properties">
          <!-- 属性详情 -->
          <view class="property-group">
            <view class="group-title">基础信息</view>
            <view class="item">
              <text class="label">科属</text>
              <text class="value">{{ treeDetail.familyName }} {{ treeDetail.genusName }}</text>
            </view>
            <view class="item">
              <text class="label">保护等级</text>
              <text class="value protection">{{ treeDetail.protectionLevel }}级</text>
            </view>
          </view>

          <view class="property-group">
            <view class="group-title">位置信息</view>
            <view class="item">
              <text class="label">经纬度</text>
              <text class="value">{{ treeDetail.gpsLongitude }}, {{ treeDetail.gpsLatitude }}</text>
            </view>
            <view class="item">
              <text class="label">省市区</text>
              <text class="value">{{ treeDetail.provinceName }} - {{ treeDetail.cityName }} - {{ treeDetail.districtName
                }}</text>
            </view>
            <view class="item">
              <text class="label">详细地址</text>
              <text class="value">{{ treeDetail.locationAddress }}</text>
            </view>
          </view>

          <view class="property-group">
            <view class="group-title">其他信息</view>
            <view class="item">
              <text class="label">描述</text>
              <text class="value description">{{ treeDetail.description || '暂无描述' }}</text>
            </view>
            <view class="item">
              <text class="label">更新时间</text>
              <text class="value">{{ treeDetail.updateTime }}</text>
            </view>
          </view>
        </view>

        <!-- 二维码 -->
        <view class="qr-section" v-if="treeDetail.qrCodeUrl">
          <view class="qr-title">古树信息二维码</view>
          <view class="qr-container">
            <image mode="widthFix" :src="treeDetail.qrCodeUrl" class="qr-code"></image>
          </view>
          <text class="qr-desc">扫码查看古树详细信息</text>
        </view>
      </view>
    </view>

    <!-- 同类古树推荐 -->
    <view class="similar panel">
      <view class="title">
        <text class="title-text">同类推荐</text>
        <view class="title-line"></view>
      </view>
      <view class="content">
        <navigator v-for="item in similarTrees" :key="item.id" class="goods" hover-class="navigator-hover"
          :url="`/pages/tree/treeDetail?id=${item.id}`">
          <image class="image" mode="aspectFill" :src="item.imageUrl"></image>
          <view class="name ellipsis">{{ item.name }}</view>
          <view class="age">
            <text class="age-icon">🕐</text>
            {{ item.age }}年
          </view>
          <view class="location">
            <text class="location-icon">📍</text>
            {{ item.location }}
          </view>
        </navigator>

        <view class="no-more" v-if="similarTrees.length === 0">
          暂无同类古树推荐
        </view>
      </view>
    </view>

    <!-- 发现异常按钮 -->
    <view class="report-btn-container">
      <button class="report-btn" @tap="onReportIssue">
        <text class="report-icon">⚠️</text>
        发现异常
      </button>
    </view>
  </scroll-view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getTreeDetailAPI } from '@/services/tree'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const scanData = ref('')
const treeDetail = ref({
  mediaList: []
})

// 模拟同类古树数据
const similarTrees = ref([
  {
    id: 1,
    name: "千年银杏",
    age: 1200,
    location: "浙江省杭州市",
    imageUrl: "https://yanxuan-item.nosdn.127.net/e0cea368f41da1587b3b7fc523f169d7.png"
  },
  {
    id: 2,
    name: "古槐树",
    age: 800,
    location: "山东省泰安市",
    imageUrl: "https://yanxuan-item.nosdn.127.net/e0cea368f41da1587b3b7fc523f169d7.png"
  },
  {
    id: 3,
    name: "迎客松",
    age: 1500,
    location: "安徽省黄山市",
    imageUrl: "https://yanxuan-item.nosdn.127.net/e0cea368f41da1587b3b7fc523f169d7.png"
  },
  {
    id: 4,
    name: "古榕树",
    age: 600,
    location: "福建省福州市",
    imageUrl: "https://yanxuan-item.nosdn.127.net/e0cea368f41da1587b3b7fc523f169d7.png"
  }
])

// 使用 uni-app 的 onLoad 钩子接收参数
onLoad(async (options) => {
  if (options && options.data) {
    scanData.value = decodeURIComponent(options.data)

    // 简单的参数解析方法
    try {
      const getQueryParam = (url, param) => {
        const queryString = url.split('?')[1] || ''
        const pairs = queryString.split('&')
        for (let pair of pairs) {
          const [key, value] = pair.split('=')
          if (key === param) {
            return decodeURIComponent(value || '')
          }
        }
        return null
      }

      const treeId = getQueryParam(scanData.value, 'treeId')
      console.log('treeId', treeId)

      if (treeId) {
        // 将 treeId 作为参数传递给 API
        const res = await getTreeDetailAPI(treeId)

        // 检查响应数据是否为 null 或 undefined
        if (res && res.data) {
          treeDetail.value = res.data
          console.log('res', res)
        } else {
          // 数据为 null 时的处理
          setTimeout(() => {
            uni.showToast({
              title: '未找到古树信息',
              icon: 'none'
            })
          }, 1000)
          console.warn('获取到的古树数据为空')
          // 设置默认值
          //返回上一页
          uni.navigateBack()

        }
      } else {
        uni.showToast({
          title: '参数无效',
          icon: 'none'
        })
        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 500)
      }
    } catch (error) {
      uni.showToast({
        title: '获取数据失败',
        icon: 'none'
      })
      console.error('获取古树详情失败:', error)
    }
  }
})
// 处理swiper切换
const currentIndex = ref(0)
const handleSwiperChange = (e) => {
  currentIndex.value = e.detail.current
}

// 点击图片预览
const onTapImage = (url) => {
  //大图预览
  uni.previewImage({
    current: url,
    urls: treeDetail.value.mediaList.map(item => item.mediaUrl)
  })
}

// 图片加载错误处理
const onImageError = (item) => {
  console.error('图片加载失败:', item)
  uni.showToast({
    title: '图片加载失败',
    icon: 'none'
  })
}
// 发现异常按钮点击处理
const onReportIssue = () => {
  // 跳转到报告异常页面，并传递古树信息
  uni.navigateTo({
    url: `/pages/index/ReportIssue/ReportIssue?treeInfo=${encodeURIComponent(JSON.stringify(treeDetail.value))}`
  })
}
// 添加志愿活动按钮点击处理
const onAddVolunteerActivity = () => {
  // 跳转到志愿活动页面，并传递古树信息
  uni.navigateTo({
    url: `/pages/voluntary/addvoluntary/addvoluntary?treeInfo=${encodeURIComponent(JSON.stringify(treeDetail.value))}`
  })
}

</script>

<style lang="scss">
.viewport {
  background-color: #f5f5f5;
  padding-bottom: 120rpx; // 为底部按钮留出空间
}

/* 商品信息 */
.goods {
  background-color: #fff;
  margin-bottom: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;

  .preview {
    height: 600rpx;
    position: relative;

    .swiper {
      width: 100%;
      height: 100%;
    }

    .image {
      width: 100%;
      height: 100%;
    }

    .indicator {
      height: 40rpx;
      padding: 0 24rpx;
      line-height: 40rpx;
      border-radius: 30rpx;
      color: #fff;
      font-family: Arial, Helvetica, sans-serif;
      background-color: rgba(0, 0, 0, 0.3);
      position: absolute;
      bottom: 30rpx;
      right: 30rpx;

      .current {
        font-size: 28rpx;
      }

      .split {
        font-size: 24rpx;
        margin: 0 1rpx 0 2rpx;
      }

      .total {
        font-size: 24rpx;
      }
    }
  }

  .meta {
    position: relative;
    padding: 30rpx;

    .name-wrapper {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      .name {
        max-height: 88rpx;
        line-height: 1.4;
        font-size: 36rpx;
        color: #333;
        font-weight: bold;
        flex: 1;
      }

      .age-badge {
        background: linear-gradient(45deg, #35c8a9, #2a9d8f);
        color: white;
        padding: 8rpx 16rpx;
        border-radius: 30rpx;
        font-size: 24rpx;
        font-weight: bold;
        white-space: nowrap;
      }
    }

    .ellipsis {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .desc {
      line-height: 1.6;
      font-size: 28rpx;
      color: #666;
      margin-bottom: 20rpx;

      .age-icon {
        margin-right: 10rpx;
      }
    }

    .protection-level {
      .level-tag {
        background-color: #fff9e6;
        color: #e6a23c;
        padding: 6rpx 16rpx;
        border-radius: 30rpx;
        font-size: 24rpx;
        border: 1rpx solid #f9e6b6;
      }
    }
  }
}

/* 商品详情 */
.detail {
  background-color: #fff;
  margin-bottom: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
  padding: 0 30rpx 30rpx;

  .title {
    padding: 30rpx 0;
    position: relative;

    .title-text {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      position: relative;
      z-index: 1;
      padding-left: 20rpx;
      border-left: 8rpx solid #35c8a9;
    }

    .title-line {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 2rpx;
      background: linear-gradient(to right, #35c8a9, transparent);
    }
  }

  .content {
    .properties {
      padding: 20rpx 0;

      .property-group {
        margin-bottom: 30rpx;

        .group-title {
          font-size: 28rpx;
          color: #35c8a9;
          font-weight: bold;
          margin: 20rpx 0;
          padding-left: 10rpx;
          border-left: 6rpx solid #35c8a9;
        }
      }

      .item {
        display: flex;
        line-height: 2;
        padding: 15rpx 20rpx;
        font-size: 26rpx;
        color: #333;
        border-bottom: 1rpx dashed #eee;
        transition: background-color 0.3s;

        &:last-child {
          border-bottom: none;
        }

        &:active {
          background-color: #f9f9f9;
        }
      }

      .label {
        width: 180rpx;
        font-weight: bold;
        color: #666;
      }

      .value {
        flex: 1;
        color: #333;

        &.protection {
          color: #e6a23c;
          font-weight: bold;
        }

        &.description {
          line-height: 1.6;
        }
      }
    }

    .qr-section {
      text-align: center;
      padding: 30rpx 0;

      .qr-title {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 20rpx;
      }

      .qr-container {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 20rpx;
      }

      .qr-code {
        width: 300rpx;
        height: 300rpx;
        border: 10rpx solid #fff;
        box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
      }

      .qr-desc {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

/* 同类推荐 */
.similar {
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
  padding: 0 30rpx 30rpx;
  margin-bottom: 30rpx;

  .title {
    padding: 30rpx 0;
    position: relative;

    .title-text {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      position: relative;
      z-index: 1;
      padding-left: 20rpx;
      border-left: 8rpx solid #35c8a9;
    }

    .title-line {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 2rpx;
      background: linear-gradient(to right, #35c8a9, transparent);
    }
  }

  .content {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .goods {
      width: calc(50% - 15rpx);
      padding: 20rpx;
      margin-top: 20rpx;
      border-radius: 15rpx;
      background-color: #fafafa;
      box-sizing: border-box;
      transition: all 0.3s;

      &:active {
        transform: translateY(-5rpx);
        box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.1);
      }
    }

    .image {
      width: 100%;
      height: 260rpx;
      border-radius: 10rpx;
      margin-bottom: 15rpx;
    }

    .name {
      height: 70rpx;
      margin: 10rpx 0;
      font-size: 26rpx;
      color: #333;
      font-weight: bold;
    }

    .age,
    .location {
      font-size: 22rpx;
      color: #999;
      margin-bottom: 5rpx;

      .age-icon,
      .location-icon {
        margin-right: 5rpx;
      }
    }

    .no-more {
      width: 100%;
      text-align: center;
      padding: 50rpx 0;
      color: #999;
      font-size: 28rpx;
    }
  }

  .navigator-hover {
    background-color: #f0f0f0;
  }
}

.no-image {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
  color: #ccc;

  .iconfont {
    font-size: 100rpx;
    margin-bottom: 20rpx;
  }

  .no-image-text {
    color: #999;
    font-size: 28rpx;
  }
}

// 发现异常按钮
.report-btn-container {
  position: fixed;
  bottom: 30rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  max-width: 650rpx;
  z-index: 999;
}

.report-btn {
  background: linear-gradient(45deg, #ff6b6b, #ff8e53);
  color: white;
  border: none;
  border-radius: 50rpx;
  padding: 20rpx 0;
  font-size: 32rpx;
  font-weight: bold;
  box-shadow: 0 10rpx 20rpx rgba(255, 107, 107, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;

  .report-icon {
    margin-right: 10rpx;
  }

  &:active {
    transform: scale(0.98);
  }
}

// 响应式优化
@media screen and (max-width: 350px) {
  .similar .content .goods {
    width: 100%;
  }
}

.form-button {
  height: 80rpx;
  text-align: center;
  line-height: 80rpx;
  margin: 30rpx 20rpx;
  color: #fff;
  border-radius: 80rpx;
  font-size: 30rpx;
  background-color: #27ba9b;
}
</style>